package demo.java.net;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class TCPServer {

    private static Logger logger = LoggerFactory.getLogger(TCPServer.class);

    public static void main(String s[]) {
        logger.info("begin");
        new TCPServer(8080);
    }

    ServerSocket serverSocket;
    Socket socket;
    BufferedReader bufferedReader;
    PrintWriter printWriter;

    String str[] = { "1111", "2222", "3333", "4444", "5555", "6666", "7777", "8888", "9999", "1010" };

    void init(int port) {
        try {
            serverSocket = new ServerSocket(port);
            logger.info("成功监听端口：{}", port);
            socket = serverSocket.accept();

            InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream();

            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);

            bufferedReader = new BufferedReader(inputStreamReader);
            printWriter = new PrintWriter(outputStream, true);
        } catch (Exception e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }

    }

    void process() {
        try {
            for (int i = 0; i < 10; i++) {
                System.out.println("111111111");
                String message = bufferedReader.readLine();
                System.out.println(message);
                printWriter.println(str[i]);
                Thread.sleep(1000);
            }
            socket.close();
            serverSocket.close();
        } catch (Exception e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
    }

    public TCPServer(int port) {
        init(port);
        process();
    }

}